﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Grain.Crm.DataMigrator.CrmServices;

namespace Grain.Crm.DataMigrator.Imports
{
    public abstract class ImportBase
    {
        public string FileContent;
        public string HeaderRow;
        public string ThisEntityName;
        public string XlsFilename;

        protected CrmService _service;
        protected WhoAmIResponse _whoAmIResponse;
        protected importfile ImportFile;
        protected Guid ImportId;
        protected ImportPayload ImportPayload { get; set; }


        public ImportBase(CrmService service, WhoAmIResponse whoAmIResponse, ImportPayload importPayload)
        {
            _service = service;
            _whoAmIResponse = whoAmIResponse;

            ImportPayload = importPayload;

            ThisEntityName = ImportPayload.EntityName;
            XlsFilename = ImportPayload.Filename;
            FileContent = ImportPayload.ContentRow;
            HeaderRow = ImportPayload.HeaderRow;
        }

        protected abstract void Preprocess(out bool entityExists);
        protected virtual void Postprocess() { }

        public bool Execute(out Exception exception)
        {
            exception = null;
            bool success;
            
            try
            {
                IEnumerable<importlog> errLogs;
                bool entityExists;

                Console.WriteLine("Importing " + ThisEntityName);

                Preprocess(out entityExists);

                ImportsHelper.PrepareImport(_service, _whoAmIResponse, entityExists, ThisEntityName, XlsFilename, FileContent, HeaderRow, out ImportId, out ImportFile);

                var response = ImportsHelper.PerformImport(_service, ImportFile, ImportId);

                ImportsHelper.WaitForImportCompletion(_service, response);
                
                success = ImportsHelper.CheckImportResult(_service, ImportFile, out errLogs);

                Postprocess();
                if (success)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Importing done with success\n");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Importing done with errors\n");
                }
                Console.ResetColor();

            }
            catch (Exception ex)
            {
                exception = ex;
                success = false;
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Importing failed.\n");
                Console.ResetColor();
            }

            return success;
        }


    }
}
